$(document).ready(function () {



    layui.use(function () {

        var layer = layui.layer;
        queryDetail()
        queryTable()
    });
})


var curMaterialId = null;

function queryDetail() {

    new AjaxChain()
        .setUrl('/material/detail/wx/get')
        .setData({
            code: window.location.href.split('code=')[1],
        })

        .then(data => {

            curMaterialId = data.id;

            $('ul').empty().append(
                `
                    <li><div>物资名称：</div>${data.name}</li>
                    <li><div>物资编号：</div>${data.code}</li>
                    <li><div>物资类型：</div>${data.typeName}</li>
                    <li><div>当前状态：</div>${data.statusDesc}</li>
                    <li><div>上次充电时间：</div>${data.lastChargeTime || ''}</li>
                    <li><div>过期时间：</div>${data.expiryDate || ''}</li>
                    <li><div>物资规格：</div>${data.specification}</li>
                `
            )
        })
        .send();

}



function op(type) {

    switch (type) {

        case 2:

            layer.open({
                type: 1,
                area: '350px',
                move: false,
                resize: false,
                shadeClose: true,
                title: '填写充电记录',
                content: `
                <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
                    <div class="demo-login-container">
                        <div class="layui-form-item">
                            <div class="layui-input-wrap"  style="margin-bottom: 20px;">
                                <div class="layui-input-prefix">
                                    <i class="layui-icon layui-icon-username"></i>
                                </div>
                                <input type="text" name="chargeUser" value="" lay-verify="required" placeholder="操作人" lay-reqtext="请填写用户名"
                                    autocomplete="off" class="layui-input" lay-affix="clear">
                            </div>
                            <div class="layui-input-wrap">
                                <div class="layui-input-prefix">
                                    <i class="layui-icon layui-icon-time"></i>
                                </div>
                                <input type="text" name="chargeTime" id="chargeTime" value="" lay-verify="required" placeholder="充电时间" lay-reqtext="请选择充电时间"
                                    autocomplete="off" class="layui-input" lay-affix="clear">
                            </div>
                        </div>
                <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">提交</button>
              </div>
                    </div>
                </div>`,
                success: function (layero, index, that) {
                    var laydate = layui.laydate;
                    laydate.render({
                        elem: '#chargeTime',
                        type: 'datetime',
                    });

                    var form = layui.form;

                    form.render();

                    // 表单提交事件

                    form.on('submit(demo-login)', function (data) {

                        data.field.materialId = curMaterialId

                        new AjaxChain()
                            .setUrl('/material/charge/record/wx/save')
                            .setMethod('post')
                            .setData(JSON.stringify(data.field))
                            .then(data => {
                                layer.close(index)
                                layer.msg('填写成功', { icon: 1, time: 2000 });
                                queryTable()
                                queryDetail()
                            })
                            .catch(err => {
                                console.error('请求异常:', err);
                            })
                            .send();

                        return false; // 阻止默认 form 跳转

                    });

                }

            });

            break;

        default:
            break;
    }
}

queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 240
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/material/charge/record/wx/list"
            , where: {
                pageSize: 5,
                code: window.location.href.split('code=')[1],
            }
            ,limit: 5
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'chargeUser', title: '操作人', align: "center" }
                , { field: 'chargeTime', title: '充电时间', align: "center" }
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }

        });

    });
}





function ajaxPrefix() {
    return '/rest/fstation'
}


// 封装接口调用
class AjaxChain {
    constructor() {
        this.config = {
            url: '',
            type: 'GET',
            data: {},
            dataType: 'json',
            contentType: "application/json",
            layer: false, // 是否显示加载层
            layerOptions: {} // 加载层配置
        };
        this.layerId = null;
    }

    setUrl(url) {
        this.config.url = url;
        return this;
    }

    setMethod(method) {
        this.config.type = method.toUpperCase();
        return this;
    }

    setData(data) {
        this.config.data = data;
        return this;
    }

    setContentType(type) {
        this.config.contentType = type;
        return this;
    }

    // 启用加载层
    enableLayer(msg, callBack, speed) {
        var speed = speed || 100


        showProgress(msg, callBack, speed)
        return this;
    }

    // 成功回调
    then(successCallback) {
        this.config.success = (res) => {
            if (this.config.layer && this.layerId) layer.close(this.layerId);

            if (res.message === 'OK') {
                successCallback(res.result);

            } else {
                layer.msg(res, { icon: 5 });
            }
        };
        return this;
    }

    // 失败回调
    catch(errorCallback) {
        this.config.error = (xhr, status, error) => {
            if (this.config.layer && this.layerId) layer.close(this.layerId);
            errorCallback(error);
            layer.msg(res);
        };
        return this;
    }

    // 发送请求
    send(progress) {
        const _this = this;

        if (this.config.layer) {
            this.layerId = layer.open(_this.config.layerOptions);
        }

        $.ajax({
            url: ajaxPrefix() + this.config.url,
            type: this.config.type,
            data: this.config.data,
            dataType: this.config.dataType,
            contentType: this.config.contentType,

            success: this.config.success || function (res) {
                // 默认成功处理
            },
            error: this.config.error || function (xhr) {
                // 默认错误处理
            },
            complete: function () {
                if (_this.config.layer && _this.layerId) {
                    layer.close(_this.layerId);
                }
            }
        });

        return this;
    }
}

